//Copyright (c) 2010, Goodwine & Tibia ML
//Licensed under new BSD License.

var info = document.getElementsByTagName('tbody');
var i;
// Check if text should be parsed.
for(i = 1; i < info.length; i++)
{
	if(info[i].innerHTML.match(/<b>Character Information<\/b>/igm))
		link_rows(info[i].getElementsByTagName('tr'));
}
function link_rows(rows)
{
	for (var i = 0; i < rows.length; i++)
	{
		if (rows[i].firstChild)
		{
			// Add icon links to characters.
			fc = rows[i].firstChild;
			if (fc.innerHTML == 'Name:' || fc.innerHTML == 'Married to:')
			{
				var name = fc.nextSibling.innerText.match(/^(.*?)(,.*?)?\s*$/);
				// fixes ugly website of tibia because the input is outside the form
				fc.nextSibling.innerHTML = fc.nextSibling.innerHTML.replace(/(.*?<div.*?>).*?<div.*?>.*?<table.*?(<form.*?)>(<\/form>).*?\s?(<input.*?>)(.*?\s*)*$/i, '$1$2 style="margin:0;">$4$3</div>');
				name = name[1].replace(/(\xa0|&#160;|&nbsp;| )/g, '+');
        linkCharacter(fc.nextSibling, name);
        
			}
			// Add icon of sex.
			if (fc.innerHTML == 'Sex:')
			{
				sex = fc.nextSibling.textContent.toLowerCase();
				tooltip = sex.charAt(0).toUpperCase() + sex.substr(1);
				fc.nextSibling.innerHTML = '<img alt="'+tooltip+'" title="'+tooltip+'" src="'+chrome.extension.getURL("/images/"+sex+".png") +'"/> '+tooltip;
			}
			// Add icon links to world.
			if (fc.innerHTML == 'World:')
			{
				world = fc.nextSibling.textContent;
				fc.nextSibling.innerHTML = '<a href="/community/?subtopic=worlds&world=' + world + '">' + world + '</a>';
				linkWorlds(fc.nextSibling, world);
			}
			// Add house linker.
			if (fc.innerHTML == 'House:' && world)
			{
				var pattern = /^(.+?( \(.+?\))?) \((.+?)\)(.+?)$/img;
				var txt = fc.nextSibling.textContent;
				matches = pattern.exec(txt);
				if (matches.length)
				{
					house = matches[1];
					city = matches[matches.length-2];
					getworldtownhouses();
					break;
				}
			}
		}
	}
}

// Submit form to get the house list and parse the results.
function getworldtownhouses()
{
	request = new XMLHttpRequest();
	request.onreadystatechange = httprecv;
	var params = "world=" + world + "&town=" + city + "&state=&order=&type=houses";
	var url = 'http://www.tibia.com/community/?subtopic=houses';
	request.open('POST', url);
	request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	request.send(params);
	return false;
}

function isArray(obj) {
    return obj.constructor == Array;
}

// Add the link.
function httprecv()
{
	if (request.readyState != 4) return;
	var text = request.responseText;
	var m;
	var h;
	house_code = null;
	// Parse the form to get the house info.
	text = text.replace(/\r|\n/g, '');
	house = house.replace(/(\xa0|&nbsp;| )/g, '&#160;');
	var regex = new RegExp('<TR(.*?)</FORM>', 'gi');
	var regex2 = new RegExp('<TD.*?>(.*?)</', 'gi');
	var regex3 = new RegExp('<form(.*?)$', 'i');
	var found = false;
	while((m = regex.exec(text)) != null && !found)
	{
		h = m[1].match(regex2);
		if(isArray(h)){
			for(var i = 0; i<h.length; i++){
				h[i] = h[i].replace(/^.*?<NOBR>(.+?)<\/?$/gi, '$1');
				if (h[i] == house) {
					m = regex3.exec(m[1]);
					house_code = m[0];
					house_code = house_code.replace(/<td>|<tr>|<\/td>|<\/tr>/gi, '');
					found = true;
					break;
				}
			}
		}
	}
	// If succesully linked, set a text link to submit the form instead of the image 'Submit'.
	if (house_code != null)
	{
		house_code = house_code.replace(/<form action/ig, '<form name="getHouseForm" style="max-height:16px; padding: 0; margin: 0;" action');
		house_code = house_code.replace(/<input type=image.*?>/ig, '<a href="javascript: void(0);" onclick="document.getHouseForm.submit(); return false;">');
		house_code = house_code + house + "</a>" + ' (' + city + ')' + matches[matches.length-1];
		fc.nextSibling.innerHTML = house_code;
	}  
}